<?php

namespace Home\Controller;

class MsgController extends BaseController {

//    public function _initialize() {
//        //重写，勿动
//    }

    public function getList() {
        $p = I('p', 0, 'intval');

        if ($p) {
            $page = $p * 10;
        }

        $list = M('Msg')
                ->field('msg_id,title,subtitle,create_time')
                ->order('create_time desc')
                ->limit($page, 10)
                ->select();

        if (empty($list)) {

            $list = [];
        } else {
            foreach ($list as &$val) {
                $where['user_id'] = $this->user_id;
                $where['msg_id'] = $val['msg_id'];

                $is_read = M('MsgRead')->where($where)->find();

                if (empty($is_read)) {
                    $val['is_read'] = 0;
                } else {
                    $val['is_read'] = 1;
                }
            }
            unset($val);
        }

        $this->success('获取成功', $list);
    }

    public function info() {
        $msg_id = I('msg_id', 0, 'intval');

        if ($msg_id == 0) {
            $this->error('请选择正确消息');
        }

        $info = M('Msg')->field('msg_id,title,subtitle,content,create_time')->where(['msg_id' => $msg_id])->find();

        $this->success('获取成功', $info);
    }

    public function detail() {
        $id = I('id', 0, 'intval');
        if ($id == 0) {
            $this->error('错误的ID');
        }

        $where['user_id'] = $this->user_id;
        $where['msg_id'] = $id;
        $is_read = M('MsgRead')->where($where)->find();

        if (empty($is_read)) {
            M('MsgRead')->add($where);
        }

        $data = M('Msg')->where(['msg_id' => $id])->find();

        $this->assign('data', $data);
        $this->display();
    }

    public function getNotReadNum() {
        $where['user_id'] = $this->user_id;

        $msg_ids = M('MsgRead')->where($where)->getField('msg_id', true);

        $data['not_read_num'] = 0;
        if ($msg_ids) {
            $msgWhere['msg_id'] = array('not in', $msg_ids);
            $data['not_read_num'] = M('Msg')->where($msgWhere)->count();
        } else {
            $data['not_read_num'] = M('Msg')->count();
        }


        $this->success('获取成功', $data);
    }

}
